﻿@Cofe ?= {}

$ = jQuery
utils = Cofe.utils
Entry = Cofe.Entry
EntryItem = Cofe.EntryItem
EntryList = Cofe.EntryList

#http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/
uploadSupport = 
  dragEnter : (event) ->
    event.stopPropagation();
    event.preventDefault();
    @

  dragExit : (event) ->
    event.stopPropagation();
    event.preventDefault();
    @

  dragOver : (event) ->
    
    event.stopPropagation();
    event.preventDefault();
    @

  drop : (event, dis) =>
    event.stopPropagation();
    event.preventDefault();

    files = event.dataTransfer.files
    count = files.length

    if dis.rootEntryItem isnt null and  count > 0
       str1 = "Uploading " + count.toString() + " items"
       utils.notify("Upload", str1)
       formData = new FormData();
       for f, idx in files
         formData.append('file[' + idx + ']', f)
       $.ajax({
         url: dis.rootEntryItem.links.self.url + "/upload"
         type: 'POST'
         data : formData
         cache: false
         contentType : false
         processData : false 
         success : (xhr, s, e) => 
           str2 = "Uploaded " + count.toString() + " items"
           utils.notify("Upload", str2)
           newItems = EntryList.fromJson(xhr, null)
           for e in newItems.entries
             ei = dis.entryItemList.entryItemConstructor(e)
             console.log ei
             dis.entryItemList.addItem(ei, 0)
           #dis.entryItemList.reload()
         error : () => console.log "error"
       })
      
    @


  initUploadSupport : (el, rootEntryItem) ->
    @rootEntryItem = rootEntryItem
    dropBox = $("#dropbox", el)
    if dropBox isnt undefined
      dropbox.addEventListener("dragenter", @dragEnter)
      dropbox.addEventListener("dragexit", @dragExit)
      dropbox.addEventListener("dragover", @dragOver)
      dis = @
      dropbox.addEventListener("drop", (event) => @drop(event, dis))

Cofe.uploadSupport = uploadSupport